from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query, Path, Depends, UploadFile, File
from app.schemas.news import *
from app.crud.news import news_crud
from app.models.models import *
import os
import uuid

router = APIRouter(tags=["咨询与公告管理"])


@router.post(path="", response_model=NewsResponse, summary="创建公告")
async def create_news(news_data: NewsCreate):
    """创建公告"""
    try:
        news = await news_crud.create(news_data)
        # 获取分类名称
        category = await Dictionary.get_or_none(id=news.category_id)
        result = NewsResponse(
            id=news.id,
            title=news.title,
            cover_image=news.cover_image,
            abstract=news.abstract,
            content=news.content,
            is_top=news.is_top,
            tags=news.tags,
            category_id=news.category_id,
            category_name=category.name if category else None,
            created_at=news.created_at,
            updated_at=news.updated_at,
            is_deleted=news.is_deleted
        )
        return result
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建失败,{str(e)}")


@router.put(path="/{news_id}", response_model=NewsResponse, summary="更新公告")
async def update_news(news_id: int, news_data: NewsUpdate):
    """更新公告"""
    try:
        news = await news_crud.update(news_id, news_data)
        # 获取分类名称
        category = await Dictionary.get_or_none(id=news.category_id)
        result = NewsResponse(
            id=news.id,
            title=news.title,
            cover_image=news.cover_image,
            abstract=news.abstract,
            content=news.content,
            is_top=news.is_top,
            tags=news.tags,
            category_id=news.category_id,
            category_name=category.name if category else None,
            created_at=news.created_at,
            updated_at=news.updated_at,
            is_deleted=news.is_deleted
        )
        return result
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新失败,{str(e)}")


@router.delete("/{news_id}", summary="删除公告")
async def delete_news(news_id: int):
    """删除公告"""
    try:
        deleted = await news_crud.delete(news_id)
        if deleted:
            return {"message": "删除成功"}
        else:
            raise HTTPException(status_code=404, detail="公告不存在")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除失败,{str(e)}")


@router.get("/{news_id}", response_model=NewsResponse)
async def get_news_by_id(news_id: int):
    """通过ID获取公告"""
    try:
        news = await news_crud.get_news_by_id(news_id)
        if news:
            # 获取分类名称
            category = await Dictionary.get_or_none(id=news.category_id)
            result = NewsResponse(
                id=news.id,
                title=news.title,
                cover_image=news.cover_image,
                abstract=news.abstract,
                content=news.content,
                is_top=news.is_top,
                tags=news.tags,
                category_id=news.category_id,
                category_name=category.name if category else None,
                created_at=news.created_at,
                updated_at=news.updated_at,
                is_deleted=news.is_deleted
            )
            return result
        else:
            raise HTTPException(status_code=404, detail="公告不存在")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取失败,{str(e)}")


@router.get("/", response_model=NewsPaginationResponse)  # 响应模型改为分页模型
async def get_news_list(
        skip: int = 0,
        limit: int = 10,
        category_id: Optional[int] = None,
        search: Optional[str] = None,
        is_top: Optional[bool] = None
):
    """获取公告列表（带分页）"""
    try:
        # 获取当前页数据和总记录数
        news_list, total = await news_crud.get_news_list_with_total(
            skip=skip,
            limit=limit,
            category_id=category_id,
            search=search,
            is_top=is_top
        )

        # 添加分类名称到每个新闻项
        news_response_list = []
        for news in news_list:
            category = await Dictionary.get_or_none(id=news.category_id)
            news_response = NewsResponse(
                id=news.id,
                title=news.title,
                cover_image=news.cover_image,
                abstract=news.abstract,
                content=news.content,
                is_top=news.is_top,
                tags=news.tags,
                category_id=news.category_id,
                category_name=category.name if category else None,
                created_at=news.created_at,
                updated_at=news.updated_at,
                is_deleted=news.is_deleted
            )
            news_response_list.append(news_response)

        # 返回分页数据
        return {
            "items": news_response_list,
            "total": total,
            "skip": skip,
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取公告列表失败: {str(e)}")


@router.get("/search/", response_model=NewsPaginationResponse)
async def search_news(
        keyword: str = Query(..., description="搜索关键词"),
        skip: int = Query(0, description="跳过的记录数"),
        limit: int = Query(10, description="返回的记录数"),
        category_id: int = Query(None, description="分类ID")
):
    """搜索公告（带分页）"""
    try:
        # 获取搜索结果和总记录数
        news_list, total = await news_crud.search_news_with_total(
            keyword=keyword,
            skip=skip,
            limit=limit,
            category_id=category_id
        )

        # 添加分类名称到每个新闻项
        news_response_list = []
        for news in news_list:
            category = await Dictionary.get_or_none(id=news.category_id)
            news_response = NewsResponse(
                id=news.id,
                title=news.title,
                cover_image=news.cover_image,
                abstract=news.abstract,
                content=news.content,
                is_top=news.is_top,
                tags=news.tags,
                category_id=news.category_id,
                category_name=category.name if category else None,
                created_at=news.created_at,
                updated_at=news.updated_at,
                is_deleted=news.is_deleted
            )
            news_response_list.append(news_response)

        # 返回分页数据
        return {
            "items": news_response_list,
            "total": total,
            "skip": skip,
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"搜索公告失败: {str(e)}")


# 添加文件上传端点
@router.post("/upload-image/", summary="上传图片")
async def upload_image(file: UploadFile = File(...)):
    """上传图片文件并返回URL"""
    try:
        # 创建上传目录（如果不存在）
        upload_dir = "uploads"
        os.makedirs(upload_dir, exist_ok=True)

        # 生成唯一文件名
        file_extension = os.path.splitext(file.filename)[1]
        unique_filename = f"{uuid.uuid4()}{file_extension}"
        file_path = os.path.join(upload_dir, unique_filename)

        # 保存文件
        with open(file_path, "wb") as buffer:
            content = await file.read()
            buffer.write(content)

        # 返回文件URL
        file_url = f"/{file_path}"
        return {"url": file_url}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"上传失败: {str(e)}")





